<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>10_ComponentLife</title>
  </head>
  <body>
    <div id="example"></div>

    <script type="text/javascript" src="../js/react.development.js"></script>
    <script
      type="text/javascript"
      src="../js/react-dom.development.js"
    ></script>
    <script type="text/javascript" src="../js/babel.min.js"></script>
    <script type="text/babel">
      /*
      需求: 自定义组件
        1. 让指定的文本做显示/隐藏的动画
        2. 切换时间为2S
        3. 点击按钮从界面中移除组件界面
      */
      class Fade extends React.Component {
        constructor(props) {
          super(props)
          console.log('constructor(): 创建组件对象')
          this.state = {
            opacity: 1
          }
          this.removeComponent = this.removeComponent.bind(this)
        }

        componentWillMount() {
          console.log('componentWillMount(): 初始化将要挂载')
        }

        componentDidMount() {
          // 在此方法中启动定时器/绑定监听/发送ajax请求
          console.log('componentDidMount(): 初始化已经挂载')
          // 保存到当前组件对象中
          this.intervalId = setInterval(
            function() {
              console.log('--------')
              // 得到当前opacity
              let { opacity } = this.state
              // 更新opacity
              opacity -= 0.1
              if (opacity <= 0) {
                opacity = 1
              }
              // 更新状态
              this.setState({ opacity })
            }.bind(this),
            200
          )
        }

        componentWillUpdate() {
          console.log('componentWillUpdate(): 将要更新')
        }
        componentDidUpdate() {
          console.log('componentDidUpdate(): 已经更新')
        }

        componentWillUnmount() {
          // 清除定时器/解除监听
          console.log('componentWillUnmount(): 将要被移除')
          clearInterval(this.intervalId)
        }

        removeComponent() {
          ReactDOM.unmountComponentAtNode(document.getElementById('example'))
        }

        render() {
          console.log('render() 渲染组件')
          return (
            <div>
              <h2 style={{ opacity: this.state.opacity }}>
                {this.props.content}
              </h2>
              <button onClick={this.removeComponent}>不活了</button>
            </div>
          )
        }
      }
      ReactDOM.render(
        <Fade content="react学不会, 怎么办?" />,
        document.getElementById('example')
      )
    </script>
  </body>
</html>
